package com.snap.vseries.ui;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.snap.vseries.AppConfig;
import com.snap.vseries.R;
import com.snap.vseries.base.BaseActivity;
import com.snap.vseries.bean.ExpInfo;
import com.snap.vseries.bean.ProgramSection;
import com.snap.vseries.bean.ProgramStage;
import com.snap.vseries.fragment.ProgramFragment;
import com.snap.vseries.manager.FileManager;
import com.snap.vseries.model.DBManager;
import com.snap.vseries.service.ExpController;
import com.snap.vseries.service.PcrService;
import com.snap.vseries.ui.widget.DialogView;
import com.snap.vseries.utils.AutoUtil;
import com.snap.vseries.utils.FileUtils;
import com.snap.vseries.utils.ToastUtils;
import com.snap.vseries.utils.TopTitleUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TemplateStartActivity extends BaseActivity {
    @BindView(R.id.exp_name_et)
    EditText expNameEt;
    @BindView(R.id.exp_name_tv)
    TextView expNameTv;
    @BindView(R.id.sample_name_tv)
    TextView sampleNameTv;
    @BindView(R.id.sample_name_et)
    EditText sampleNameEt;
    @BindView(R.id.programs_tv)
    TextView programsTv;
    @BindView(R.id.plan_time_tv)
    TextView planTimeTv;
    @BindView(R.id.container)
    FrameLayout container;
    private ExpInfo expInfo;
    public ExpController expController;
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            PcrService.PcrBinder binder = (PcrService.PcrBinder) service;
            expController = binder.getService().getCurrentController();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        Intent intent = new Intent(this, PcrService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);

    }

    @Override
    protected void onDestroy() {
        if (expController != null) {
            expController = null;
            unbindService(connection);
        }
        super.onDestroy();
    }


    private void initData() {
        String name = getIntent().getStringExtra("name");
        expInfo = FileManager.getInstance().getTempDataByName(name);
        expInfo.setName(AutoUtil.getFileName());
    }

    private void setSampleName() {
        final DialogView dialogView = new DialogView(this);
        dialogView.setTitle(getString(R.string.fill_sample_name))
                .setEditContent("")
                .setOnClickListener(content -> {
                    sampleNameEt.setText(content);
                    sampleNameTv.setText(content);
                    expInfo.setSampleName(content);
                    dialogView.dismiss();
                }).show();
    }

    private void rename() {
        final DialogView dialogView = new DialogView(this);
        dialogView.setTitle(getString(R.string.exp_name_edit_tips))
                .setEditContent(expInfo.getName())
                .setClickSureDismissDialog(false)
                .setOnClickListener(content -> {
                    if (!FileUtils.checkFileName(content)) {
                        ToastUtils.get().showText("文件名称格式不正确!");
                        return;
                    }
                    DBManager.get().getExpByName(content, entity -> {
                        if (entity == null) {
                            expNameEt.setText(content);
                            expNameTv.setText(content);
                            expInfo.setName(content);
                            dialogView.dismiss();
                        } else {
                            ToastUtils.get().showText("实验已存在，请重新命名！");
                        }
                    });
                })
                .show();
    }

    private float getTotalTime() {
        List<ProgramStage> list = expInfo.getProgram();
        float total = 1f;
        float lastTemp = 25f;
        for (int i = 0; i < list.size(); i++) {
            ProgramStage stage = list.get(i);
            for (int k = 0; k < stage.getCycleCount(); k++) {
                for (int j = 0; j < stage.getSections().size(); j++) {
                    ProgramSection section = stage.getSections().get(j);
                    total += section.getDuration();
                    float deltaTemp = section.getTemp() - lastTemp;
                    total += Math.abs(deltaTemp) / (deltaTemp > 0 ? AppConfig.INCREASE_VELOCITY : AppConfig.DECREASE_VELOCITY);
                    lastTemp = section.getTemp();
                }
            }
        }
        return total;
    }

    private void initView() {
        new TopTitleUtils(this).setTitle("开始实验");
        expNameTv.setText(expInfo.getName());
        expNameEt.setText(expInfo.getName());
        sampleNameTv.setText(expInfo.getSampleName() == null ? "N/A" : expInfo.getSampleName());
        sampleNameEt.setText(expInfo.getSampleName() == null ? "" : expInfo.getSampleName());
        planTimeTv.setText(AutoUtil.getHourAndMin((long) getTotalTime()));
        programsTv.setText(expInfo.getTestProject());
        container.setVisibility(View.VISIBLE);
        ProgramFragment programFragment = new ProgramFragment(expInfo);
        getSupportFragmentManager().beginTransaction().add(R.id.container, programFragment).commitAllowingStateLoss();
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_template_start;
    }


    @OnClick({R.id.tv_start_experiment, R.id.exp_name_et, R.id.sample_name_et})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.tv_start_experiment:
                expInfo.setStartTime(System.currentTimeMillis());
                Logger.i("设置实验:启动");
                HomeActivity.startActivity(this);
                expController.startExp(expInfo);
                finish();
                break;
            case R.id.exp_name_et:
                rename();
                break;
            case R.id.sample_name_et:
                setSampleName();
                break;
            default:
                break;
        }
    }

}
